/**
 * 
 */
package org.gigi.security.repository.hibernate;

import java.util.List;

import org.gigi.core.Page;
import org.gigi.security.domain.User;
import org.gigi.security.repository.UserRepository;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


/**
 * UserRepository基于JPA规范的实现
 *
 * @author Eugene Wang 2011-5-29
 * @see
 */
@Repository
public class HibernateUserRepository implements UserRepository {
	@Autowired
	private SessionFactory sessionFactory;
	/**
	 * 获取当前Session
	 * @return
	 */
	private Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	/* (non-Javadoc)
	 * @see org.gigi.security.repository.UserRepository#save(org.gigi.security.domain.User)
	 */
	public void create(User user) {
		getSession().save(user);
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.repository.UserRepository#update(org.gigi.security.domain.User)
	 */
	public void update(User user) {
		getSession().update(user);
	}


	/* (non-Javadoc)
	 * @see org.gigi.security.repository.UserRepository#getPage(org.gigi.core.PageArgument)
	 */
	@SuppressWarnings("unchecked")
	public Page<User> getPage(Page<User> page) {
		Long count = (Long) getSession().createQuery("select count(username) from User u").uniqueResult();
		Query query = getSession().createQuery("select u from User u");
		query.setFirstResult(page.getStart());
		query.setMaxResults(page.getLimit());
		List<User> list = query.list();
		page.setData(list);
		page.setTotalCount(count);
		return page;
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.repository.UserRepository#load(java.lang.Long)
	 */
	public User findByUsername(String username) {
		return (User) getSession().get(User.class, username);
	}

	/* (non-Javadoc)
	 * @see org.gigi.security.repository.UserRepository#remove(org.gigi.security.domain.User)
	 */
	public void delete(User user) {
		getSession().delete(user);
	}
}
